package com.example.hibernate.demo.service;

import com.example.hibernate.demo.entity.Project;
import com.example.hibernate.demo.repository.ProjectRepository;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ProjectService {
    
    private final ProjectRepository projectRepository;
    
    @Transactional(readOnly = true)
    public List<Project> findAll() {
        return projectRepository.findAll();
    }
    
    @Transactional(readOnly = true)
    public Project findById(Long id) {
        return projectRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("Project not found with id: " + id));
    }
    
    @Transactional(readOnly = true)
    public Project findByIdWithEmployees(Long id) {
        return projectRepository.findByIdWithEmployees(id);
    }
    
    @Transactional(readOnly = true)
    public List<Project> findByStatus(Project.ProjectStatus status) {
        return projectRepository.findByStatus(status);
    }
    
    @Transactional(readOnly = true)
    public List<Project> findActiveProjects() {
        return projectRepository.findActiveProjectsAtDate(LocalDate.now());
    }
    
    @Transactional(readOnly = true)
    public List<Project> findByEmployeeId(Long employeeId) {
        return projectRepository.findByEmployeeId(employeeId);
    }
    
    @Transactional
    public Project save(Project project) {
        return projectRepository.save(project);
    }
    
    @Transactional
    public Project update(Long id, Project projectDetails) {
        Project project = findById(id);
        project.setName(projectDetails.getName());
        project.setDescription(projectDetails.getDescription());
        project.setStartDate(projectDetails.getStartDate());
        project.setEndDate(projectDetails.getEndDate());
        project.setStatus(projectDetails.getStatus());
        return projectRepository.save(project);
    }
    
    @Transactional
    public void delete(Long id) {
        Project project = findById(id);
        projectRepository.delete(project);
    }
}